import { PageConfig } from 'next';
import anylogger from 'anylogger';
import '@mmstudio/an000042';
import an48 from '@mmstudio/an000048';
import { tbtb001 } from '../../../atoms/db';

const logger = anylogger('pages/api/lesson/add.api');

export type Result = {
	ok: true;
} | {
	ok: false;
	message: string;
};

export type Message = {
	name: string;
	age: number;
	birthday: string;
}

/**
 * pages/api/lesson/add.api
 */
const handler = an48<Result>();

handler.post(async (req, res) => {
	try {
		logger.debug('msg body:', req.body);
		const { name, age, birthday } = req.body as Message;
		if (!name || !age || !birthday) {
			res.status(200).json({
				ok: false,
				message: '参数缺失'
			});
			return;
		}
		await tbtb001()
			.insert({
				fd1: name,
				fd2: age,
				fd3: Number(birthday)
			});

		res.status(200).json({ ok: true });
	} catch (error) {
		logger.error(error);
		logger.trace(error);
		res.status(200).json({ ok: false, message: (error as Error).message });
	}
});

export const config = {} as PageConfig;

export default handler;
